#!/usr/bin/env python
# -*- coding: UTF-8 -*-


from django.core.management import setup_environ
import settings
setup_environ(settings)
from django.core.files import File
from django.core.exceptions import ObjectDoesNotExist
from django.db import IntegrityError

from psp.models import *
import sys


def readFile(fName):
    """
    Reads list of politicians and their URLs to http://www.nasipolitici.cz
    returns list of tupples
    """

    retVal = []
    file = open(fName, 'r')
    for line in file.readlines():
        l = line.split(' : ')
        link = l[0]
        name = l[1]
        link.strip()
        name.strip()
        retVal.append((link, name))

    file.close()

    return retVal


def processName(name):
    """
    Returns tupple of name, surname
    """

    nameSurname = ''
    for i in name.split():
        if i.find('.') == -1:
            i.strip()
            i.strip(',')
            nameSurname += i
            nameSurname += ' '
        

    nameSurname = nameSurname.strip()
    name = ''
    surname = ''
    i = 0
    for p in nameSurname.split():
        if i == 0:
            name = p
        else:
            surname += p + ' '

        i += 1

    name = name.strip()
    name = name.strip(',')
    surname = surname.strip()
    surname = surname.strip(',')

    print name, surname

    return (name, surname,)


def findCandidates(name, surname):
    candidates = Person.objects.filter(
                    name = name,
                    surname = surname
                )

    return candidates
    

def printMenu(linkName, candidates):
    link, fullName = linkName
    print "Vyber spravneho kandidata pro: %s" % fullName

    i = 0
    for c in candidates:
        print "\t%d) %s %s %s %s" % (
            i,
            c.title,
            c.name,
            c.surname,
            c.titleLast
        )
        i = i + 1

    a = int(input())
    myCandidate = candidates[a]
    myCandidate.nasiPoliticiUrl = link
    myCandidate.save()

def main():
    nasiPolitici = readFile('/tmp/seznam-politiku.txt')
    
    for i in nasiPolitici:
        link, fullName = i
        name, surname = processName(fullName)
        candidates = findCandidates(name, surname)

        if len(candidates) == 1:
            c = candidates[0]
            c.nasiPoliticiUrl = link
            print "saving: %s %s %s" % (c.name, c.surname, link)
            c.save()
        elif len(candidates) > 1:
            printMenu(i, candidates)
        #else:
        #   print "no MP found for: %s %s" % (link, fullName)
        

if __name__ == '__main__':
    main()
    sys.exit()

